<?php

class community_Model_MBookComment
{
    private $_connection=null;
    private $_db=null;
    private $_collection=null;
    private $_function=null;

    public function  __construct()
    {
        $this->_connection=new Mongo();
        $this->_db=$this->_connection->bookstore;
        $this->_collection=$this->_db->bookinterest;
        $this->_function=new Default_Model_MFunction();
    }

    public function getComments(&$total, $currentpage=1,$pagesize=10,$lengthtitle=80)
    {
        if(!is_int($currentpage) || !is_int($pagesize))
            return array();
        if($pagesize <=0)
            return array();

        if($currentpage<=0)
            $currentpage=1;
        
        $arrTemp=$this->_collection->find(array("comment"=>array('$exists'=>true)))->sort(array("datecomment"=>-1))
                ->skip(($currentpage-1)*$pagesize)->limit($pagesize);
        $bookcomment=array();
        $bookCollection=$this->_db->book;
        foreach($arrTemp as $book)
        {
            if(!isset($book["comment"]) || count($book["comment"])==0)
            {
                continue;
            }
            $arrDate=$this->_function->stringDateToArray($book["datecomment"]);
            $date=$arrDate["day"].'/'.$arrDate["month"].'/'.$arrDate["year"].' '.$arrDate["hour"].':'.$arrDate["minute"].':'.$arrDate["second"];
            $docuImage=$bookCollection->findOne(array("_id"=>new MongoId($book["id_book"])),array("image"=>true));
            $image=$docuImage["image"];

            // xac dinh comment moi nhat 
            $index=1;
            $max=1;
            for($i=0;$i<count($book["comment"]);$i++)
            {
                if((int)$book["comment"][$i]["stt"]>=$max)
                {
                    $max=(int)$book["comment"][$i]["stt"];
                    $index=$i;
                }
            }
            $comment=$book["comment"][$index]["content"];
            if(strlen($comment)>$lengthtitle)
            {
                $pos=strpos($comment, " ", $lengthtitle);
                if($pos!=False)
                {
                    $comment = substr($comment, 0,$pos+1).'...';
                }
            }

            $bookTemp=array("_id"=>$book["id_book"],"image"=>$image,"sumcomment"=>$book["sumcomment"],
                "view"=>$book["view"],"date"=>$date,"content"=>$comment);

            array_push($bookcomment, $bookTemp);
        }

        $total=count($bookcomment);
        return $bookcomment;
    }
}



